package com.zshan.clinic.common.util.uuid;

import com.zshan.clinic.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class IdBuilder {

    private static RedissonClient redissonClient;


    @Autowired
    public void setRedissonClient(RedissonClient client) {
        IdBuilder.redissonClient = client;
    }

    public static String getID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成订单号
     * @param prefix
     * @return
     */
    public static String getUniqueId(String prefix) {
        StringBuilder builder = new StringBuilder(prefix);
        builder.append(System.currentTimeMillis());
        builder.append(getFixedLengthNumber(CommonConstant.DEFAULT_5)); // 5位随机数
        long seq = nextId(builder.toString(), CommonConstant.DEFAULT_1);
        builder.append(seq);
        return builder.toString();
    }

    /**
     * 获取下一个序号
     * @param key
     * @param ttlSeconds
     * @return
     */
    private static long nextId(String key, long ttlSeconds) {
        // 拿到一个原子长整型
        RAtomicLong atomic = redissonClient.getAtomicLong(key);
        // 自增并返回
        long seq = atomic.incrementAndGet();
        // 设置过期（如果 key 新建，就会设置；如果已存在，也会刷新过期）
        atomic.expire(ttlSeconds, TimeUnit.SECONDS);
        return seq;
    }


    /**
     * 获取随机数
     * @param length
     * @return
     */
    public static String getFixedLengthNumber(int length) {
        Random random = new Random();
        int number = random.nextInt((int) Math.pow(10, length));
        return String.format("%0" + length + "d", number);
    }


    /**
     * 生成下一个序号
     * @param current
     * @return
     */
    public static String nextNo(String current) {
        if (current == null || current.isEmpty()) {
            throw new IllegalArgumentException("编号不能为空");
        }
        int i = current.length() - 1;
        while (i >= 0 && Character.isDigit(current.charAt(i))) {
            i--;
        }
        String prefix = current.substring(0, i + 1);
        String numberPart = current.substring(i + 1);
        int nextNum = Integer.parseInt(numberPart) + 1;
        String nextNumStr = String.format("%0" + numberPart.length() + "d", nextNum);
        if (nextNumStr.length() > numberPart.length()) {
            throw new IllegalArgumentException("编号已超出最大长度限制");
        }
        return prefix + nextNumStr;
    }

}
